<?php

namespace frontend\models;

use Yii;
use frontend\models\User_details;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $ip
 */
class User extends \yii\db\ActiveRecord
{
    public $user_id;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['email'], 'string', 'max' => 100],
            [['password'], 'string', 'max' => 32],
            [['ip'], 'string', 'max' => 30]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'email' => 'email',
            'password' => 'Password',
            'ip' => 'Ip',
        ];
    }

    /**
     * @添加用户
     */
    public function add_User($data)
    {
        $this->email = $data['email'];
        $this->password = $data['pwd'];
        $this->ip = $_SERVER['REMOTE_ADDR'];
        if($this->save()){
            $user_id = $this->attributes['id'];
            $res['err'] = $this->add_Details($data,$user_id);
            $res['user_id']  = $user_id;
        }else{
            $res['err'] = false;
        }
        return $res;
    }

    /**
     * @添加用户
     */
    public function add_Details($data,$user_id)
    {
        $details = New User_details();
        $details->name = $data['name'];
        $details->user_id = $user_id;
        if(!$details->save()){
            $this->del_User($user_id);
            return false;
        }else{
            return true;
        }

    }

     /**
     * @删除用户
     */
    public function del_User($user_id)
    {
        $this->findOne($user_id);
        if(!$this->delete()){
            return false;
        }else{
            return true;
        }

    }
}
